<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page.sync="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">
      <template  slot="menuLeft">
        <el-button type="primary"
            size="small"
            @click.stop="importExcel">导入订单</el-button>  
      </template>
      <template slot="ProvinceAndCity" slot-scope="{row}">
        {{row.pkgProvinceName}}省/{{row.pkgCityName}}
      </template>
      <template slot="successNums" slot-scope="{row}">
        <div v-if="row.impStatus == 'IMPORTING'">-</div>
        <div v-else-if="row.successNums>0"><el-button type="text" @click="downloadFile('success',row.bthNo)" size="mini">{{row.successNums}}</el-button></div>
        <div v-else>0</div>
      </template>
      <template slot="failedNums" slot-scope="{row}">
        <div v-if="row.impStatus == 'IMPORTING'">-</div>
        <div v-else-if="row.failedNums>0"><el-button type="text" @click="downloadFile('failed',row.bthNo)" size="mini">{{row.failedNums}}</el-button></div>
        <div v-else>0</div>
      </template>
      <template slot="chooseMoblieRule" slot-scope="{row}">
        {{dicRule[row.chooseMoblieRule]}}{{row.ruleNumber}}
      </template>
    </avue-crud>
    <el-dialog :title="'导入订单'"
               append-to-body
               :visible="box"
               :before-close="dialogClose"
               close-on-click-modal="false">
      <div>
        <div style="margin-bottom:10px">
          请下载订单模板，按格式修改后导入<el-button type="text" icon="el-icon-download" style="float:right;padding:0" @click="downloadFile('nomal')">点击下载</el-button>
        </div>
        <avue-form :option="optionChild" v-model="formChild" ref="uploadForm"></avue-form>
        <el-upload
          class="upload-demo"
          ref="upload"
          action="/api/commision-bmg/bthpackageorder/bthimport"
          :data="activityForm"
          :headers="header"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :on-success="uploadSuccess"
          :on-error="uploaderror"
          :on-change="fileChange"
          :file-list="fileList"
          :auto-upload="false"
          accept=".xls,.xlsx"
          limit="1"
          drag
          style="margin-left:120px"
          >
          <i class="el-icon-upload" style="color:#409eff"></i>
          <div class="el-upload__text"><em>上传文件</em></div>
          <div class="el-upload__tip" slot="tip">只能上传xls或xlsx文件，且不超过5Mb</div>
        </el-upload>
      </div>
       <span slot="footer" class="dialog-footer">
        <el-button @click="dialogClose">取 消</el-button>
        <el-button type="primary" @click="uploadFile">确 定</el-button>
      </span>
    </el-dialog>
  </basic-container>
</template>

<script>
  import {getList, getDetail, add, update, remove  , getSuccesFile , getFaileFile } from "@/api/commision/bthpackageorder";
  import {mapGetters} from "vuex";
  import {getToken} from '@/util/auth';
  let token = getToken()
  export default {
    data() {
      return {
        header:{
          'Blade-Auth':token
        },
        dicRule:['随机选号','尾号后一位包含数字','尾号后一位不包含数字'],
        box:false,
        form: {},
        formChild:{},
        activityForm:{},
        query: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        fileList:[],
        selectionList: [],
        option: {
          height:'auto',
          calcHeight: 30,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          refreshBtn: false,
          columnBtn: false,
          menu:false,
          dialogClickModal: false,
          align:"center",
          column: [
            {
              label: "导入批次号",
              prop: "bthNo",
              minWidth:90,
              rules: [{
                required: true,
                message: "请输入导入批次号",
                trigger: "blur"
              }]
            },
            {
              label: "导入时间",
              prop: "createTime",
              // minWidth:160,
            },
            {
              label: "文件名称",
              prop: "fileName",
              rules: [{
                required: true,
                message: "请输入文件名称",
                trigger: "blur"
              }]
            },
            {
              label: "号卡地市",
              prop: "ProvinceAndCity",
            },
            {
              label: "资费套餐所属省地区代码",
              prop: "pkgProvinceCode",
              hide: true,
              rules: [{
                required: true,
                message: "请输入资费套餐所属省地区代码",
                trigger: "blur"
              }]
            },
            {
              label: "资费套餐所属市地区代码",
              prop: "pkgCityCode",
              hide: true,
              rules: [{
                required: true,
                message: "请输入资费套餐所属市地区代码",
                trigger: "blur"
              }]
            },
            {
              label: "商户id",
              prop: "merchantId",
              hide: true,
              rules: [{
                required: true,
                message: "请输入商户id",
                trigger: "blur"
              }]
            },
            {
              label: "商户名称",
              prop: "merchantName",
              rules: [{
                required: true,
                message: "请输入商户名称",
                trigger: "blur"
              }]
            },
            {
              label: "选号规则",
              prop: "chooseMoblieRule",
              rules: [{
                required: true,
                message: "请输入选号规则",
                trigger: "blur"
              }]
            },
            // {
            //   label: "选号规则2",
            //   prop: "chooseMoblieRule2",
            //   rules: [{
            //     required: true,
            //     message: "请输入选号规则2",
            //     trigger: "blur"
            //   }]
            // },
            // {
            //   label: "选号规则3",
            //   prop: "chooseMoblieRule3",
            //   rules: [{
            //     required: true,
            //     message: "请输入选号规则3",
            //     trigger: "blur"
            //   }]
            // },
            {
              label: "状态",
              prop: "impStatus",
              dicUrl:"/api/blade-system/dict-biz/dictionary?code=COMMISION_IMPORT_STATUS",
              dicMethod:'get',
              props:{
                label:"dictValue",
                value:"dictKey"
              },
            },
            {
              label: "源文件在oss的唯一标识",
              prop: "ossId",
              hide: true,
            },
            // {
            //   label: "审核状态",
            //   prop: "chkStatus",
            // },
            // {
            //   label: "开通状态",
            //   prop: "openStatus",
            // },
            {
              label: "成功订单数量",
              prop: "successNums",
              minWidth: 100,
            },
            {
              label: "失败订单数量",
              prop: "failedNums",
              minWidth: 100,
            },
          ]
        },
        optionChild:{
          menuBtn:false,
          labelWidth:120,
          column:[
            {
              label: "商户",
              prop: "merchantId",
              span: 14,
              type:"select",
              dicUrl:"/api/merchant-bmg/merchant/list?current=1&size=100",
              dicMethod:'get',
              props:{
                label:"merchantName",
                value:"id",
                res:"data.records"
              },
              rules: [{
                required: true,
                message: "请输入商户",
                trigger: "blur"
              }]
            },
            {
              label: '号卡地市',
              prop: 'pkgCityCode',
              type: "select",
              span: 14,
              dicUrl:"/api/blade-system/dict-biz/dictionary?code=COMMISION_REGION_CODE",
              dicMethod:'get',
              props:{
                label:"dictValue",
                value:"dictKey"
              },
              rules: [{
                required: true,
                message: "必须选择号卡地市",
                trigger: "blur"
              }],
            },
            // {
            //   label: '号卡地市',
            //   prop: 'pkgCityCode',
            //   type: "cascader",
            //   span: 24,
            //   props: {
            //     label: 'name',
            //     value: 'code'
            //   },
            //   rules: [{
            //     required: true,
            //     message: "必须选择地市",
            //     trigger: "blur"
            //   }],
            //   lazy: true,
            //   lazyLoad(node, resolve) {
            //     let stop_level = 2;
            //     let level = node.level;
            //     let data = node.data || {}
            //     let code = data.code;
            //     let list = [];
            //     let callback = () => {
            //       resolve((list || []).map(ele => {
            //         return Object.assign(ele, {
            //           leaf: level >= stop_level
            //         })
            //       }));
            //     }
            //     if (level == 0) {
            //       getCity().then(res => {
            //         list = res.data.data;
            //         callback()
            //       })
            //     }
            //     if (level == 1) {
            //       getCity(code).then(res => {
            //         list = res.data.data;
            //         callback()
            //       })
            //     } else if (level == 2) {
            //       getCity(code).then(res => {
            //         list = res.data.data;
            //         callback()
            //       })
            //     }else{
            //       callback()
            //     }
            //   }
            // },
            {
              label: "选号规则",
              prop: "chooseMoblieRule",
              type:"radio",
              value:0,
              span: 24,
              dicData:[{
                    label: '随机选号',
                    value: 0
                }, {
                    label: '尾号后一位包含数字',
                    value: 1
                }, {
                    label: '尾号后一位不包含数字',
                    value: 2
                }],
              rules: [{
                required: true,
                message: "请输入商户",
                trigger: "blur"
              }],
              change:this.changeredio
            },
            {
              label:'规则数字',
              prop:"ruleNum",
              display:false,
              rules: [{
                required: true,
                message: "请输入规则数字",
                trigger: "blur"
              }],
            }
          ]
        },
        data: []
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.bthpackageorder_add, false),
          viewBtn: this.vaildData(this.permission.bthpackageorder_view, false),
          delBtn: this.vaildData(this.permission.bthpackageorder_delete, false),
          editBtn: this.vaildData(this.permission.bthpackageorder_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    methods: {
      rowSave(row, done, loading) {
        add(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowUpdate(row, index, done, loading) {
        update(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          console.log(error);
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
        // this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      onLoad(page, params = {}) {
        this.loading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      },
      importExcel(){
        this.box = true;
      },
      dialogClose(){
        this.$refs.uploadForm.resetForm();
        this.box = false;
      },
      fileChange(file,fileList){
        this.fileList = fileList;
      },
      handleRemove(file,fileList){
        this.fileList = fileList;
      },
      uploadFile(){
        this.activityForm.merchantId = this.formChild.merchantId;
        this.activityForm.merchantName = this.formChild.$merchantId;
        this.activityForm.chooseMoblieRule = this.formChild.chooseMoblieRule;
        this.activityForm.pkgCityCode = this.formChild.pkgCityCode;
        if(this.formChild.ruleNum || this.formChild.ruleNum==0){
          this.activityForm.ruleNum = this.formChild.ruleNum;
        }
        console.log(this.activityForm)
        if(!this.activityForm.merchantId){
          this.$message.error("必须选择商户");
          return;
        }else if(!this.activityForm.pkgCityCode){
          this.$message.error("必须选择号卡地市");
          return;
        }else if(!this.activityForm.chooseMoblieRule && this.activityForm.chooseMoblieRule!==0){
            this.$message.error("请选择选号规则");
            return;
        }else if(this.activityForm.chooseMoblieRule){
          if(!this.activityForm.ruleNum && this.activityForm.ruleNum!==0){
            this.$message.error("请输入规则数字");
            return;
          }
        }
        if(this.fileList.length==0){
          this.$message.error("请选择需要上传的文件");
          return;
        }
        this.$refs.upload.submit() 
      },
      // 上传成功
      uploadSuccess(response) {
        if (response.code == 200) {
          this.$message.success("文件导入成功");
          this.$refs.uploadForm.resetForm();
          this.$refs.upload.clearFiles();
          this.box = false;
          this.onLoad(this.page);
        } else {
          this.$message.error(response.msg);
        }
      },
      // 上传失败
      uploaderror(err) {
        let error = JSON.parse(err.message)
        if (err.code == "001") {
          this.$message.error("获取参数出错，请重新上传文件");
        } else {
          this.$message.error(error.msg);
        }
      },
      changeredio(row){
        let ruleNum = this.findObject(this.optionChild.column , "ruleNum");
        if(!row.value){
          ruleNum.display = false;
        }else{
          ruleNum.display = true;
        }
      },
      downloadFile(key , bthNo){
        if(key == "nomal"){
          var a = document.createElement('a'); 
          a.href = "http://jft-middleground.oss-cn-beijing.aliyuncs.com/upload/20220222/882ea06a869eced04c9a5ecb8e249913.xlsx"; 
          a.style.display = 'none';
          document.body.appendChild(a);
          a.click();
          a.remove();
        }else if(key == "success"){
          getSuccesFile(bthNo).then((res)=>{
            this.download(res.data,"导出成功订单.xlsx")
          })
        }else if(key == "failed"){
          getFaileFile(bthNo).then((res)=>{
            this.download(res.data,"导出失败订单.xlsx")
          })
        }
      },
      download(data,fileName){
          var blob = new Blob([data]); //创建一个blob对象
          var a = document.createElement('a'); //创建一个<a></a>标签
          a.href = URL.createObjectURL(blob); // response is a blob
          a.download = fileName;  //文件名称
          a.style.display = 'none';
          document.body.appendChild(a);
          a.click();
          a.remove();
      },
    }
  };
</script>

<style>
</style>
